import 'package:flutter/material.dart';
import '../../utils/api.dart';
import '../../utils/tools.dart';
import '../../application.dart';
import '../../models/category_model.dart';

class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  String _title = "全部类目";

  bool isLoading = true;
  Map<int, List<CategoryModel>> _cates;
  int _activeId = 0;

  double _itemWidth;

  @override
  void initState() {
    super.initState();
    print('init state');
    _loadCategory();
  }

  @override
  Widget build(BuildContext context) {
    _itemWidth = (MediaQuery.of(context).size.width - 100) / 3;

    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
      ),
      body: _cates == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : Container(
              color: Colors.white,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    color: Tools.greyLightColor,
                    width: 100.0,
                    child: Align(
                      alignment: Alignment.topLeft,
                      child: ListView(
                        children: _cates[0].map((item) {
                          return GestureDetector(
                            onTap: () {
                              setState(() {
                                _activeId = item.id;
                              });
                            },
                            child: Container(
                              padding:
                                  EdgeInsets.only(top: 10, bottom: 10, left: 5),
                              decoration: BoxDecoration(
                                  color: _activeId == item.id
                                      ? Colors.white
                                      : null,
                                  border: _activeId == item.id
                                      ? Border(
                                          left: BorderSide(
                                              color: Colors.pink, width: 5.0))
                                      : null),
                              child: Center(
                                child: Text(
                                  item.title,
                                  style: TextStyle(),
                                  softWrap: false,
                                ),
                              ),
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                  ),
                  Expanded(
                    child: Column(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.centerRight,
                          child: MaterialButton(
                            onPressed: () {
                              Application.route('/product/list',
                                  arguments: {'category': _activeId});
                            },
                            child: Text('全部 >>'),
                          ),
                        ),
                        Expanded(child: _buildList())
                      ],
                    ),
                  )
                ],
              ),
            ),
    );
  }

  Widget _buildList() {
    if (_activeId <= 0 ||
        _cates == null ||
        _cates.isEmpty ||
        !_cates.containsKey(_activeId)) {
      return Center(
        child: Text(
          '该类目暂无内容',
          style: TextStyle(color: Tools.greyColor),
        ),
      );
    }

    List<Widget> childs = List();
    var cate = _cates[0].firstWhere((item) => item.id == _activeId);
    if (cate != null && cate.image.isNotEmpty) {
      childs.add(
        AspectRatio(
          aspectRatio: 1.0,
          child: Padding(
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 20),
              child: Center(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Tools.image(cate.image),
                ),
              )),
        ),
      );
    }

    if (_cates[_activeId] != null &&
        _cates[_activeId] != null &&
        _cates[_activeId].isNotEmpty) {
      childs.add(Wrap(
        children: _cates[_activeId].map((item) {
          return Container(
            padding: const EdgeInsets.all(15),
            width: _itemWidth,
            child: GestureDetector(
              onTap: () {
                print('cate taped ' + item.id.toString());
                Application.route('/product/list',
                    arguments: {'category': item.id, 'top_category':item.pid});
              },
              child: Column(
                children: <Widget>[
                  ClipOval(
                    child: AspectRatio(
                      aspectRatio: 1,
                      child: Tools.image(item.image),
                    ),
                  ),
                  Text(
                    item.title,
                    style: TextStyle(fontSize: 12),
                    softWrap: false,
                  )
                ],
              ),
            ),
          );
        }).toList(),
      ));
    }
    if (childs.isEmpty) {
      return Center(
        child: Text(
          '该类目暂无内容',
          style: TextStyle(color: Tools.greyColor),
        ),
      );
    }
    return ListView(shrinkWrap: true, primary: false, children: childs);
  }

  _loadCategory() async {
    Api.post('product/get_all_cates').then((result) {
      if (result.data != null) {
        _cates = CategoryModel.mapTree(result.data);
      }
      if (result.list != null) {
        _cates = CategoryModel.mapTree(result.list);
      }
      if (_cates != null && _cates.isNotEmpty) {
        _activeId = _cates[0][0].id;
      }
      isLoading = false;

      if (!mounted) return;
      setState(() {});
    }).catchError((err) {
      print(err);
      if (!mounted) return;
      setState(() {
        isLoading = false;
      });
    });
  }
}
